<template>
    <el-card class="login-container">
        <el-form-item>
            <h4>用户登录</h4>
        </el-form-item>
        
        <el-form-item class="mylabel">
            <span>账号：</span><el-input class="custom-input" v-model="user.loginName" style="width: 240px" placeholder="请输入" /><br/>
            <span>密码：</span><el-input type="password" class="custom-input" show-password="true" v-model="user.loginPwd" style="width: 240px" placeholder="请输入" /><br/>
        </el-form-item>
            <el-button class="cus-button" type="primary" @click="loginUser">登录</el-button>
            <el-button class="cus-button" type="primary"><router-link to="/reg" class="link">注册</router-link></el-button>
    </el-card>
</template>

<script>
import axios from "../plugins/axios.js";
export default{
    data(){
        return {
            user:{
                nickName:'',
                loginName:'',
                loginPwd:''
            }
        }
    },
    methods:{
        loginUser: async function(){
            try {
                var resp = await axios.post(
                    'http://localhost:9000/user/login',`loginName=${this.user.loginName}&loginPwd=${this.user.loginPwd}`
                );
                // post请求返回的是Result数据结构
                if (resp.data.code === 2000) {
                    var u = resp.data.data;
                    //将用户信息JSON字符串保存
                    sessionStorage.setItem('user',JSON.stringify(u));
                    // 将数据上传到vuex中
                    this.$store.commit('addUser',u);
                    alert(u.nickName+"登录成功！");
                    var jwt = resp.headers.authorization;
                    sessionStorage.setItem('jwttoken',jwt);
                    this.$router.push("/ai/qianwen");
                }
            } catch (error) {
                 if (error.response && resp.data.code===4001) {
                    alert('登录失败，'+resp.data.msg);
                } else {
                    console.error('登录失败:', error);
                    alert('登录失败，请检查您的登录信息。');
                }
            }
        }
    }
}
</script>

<style scoped>
    .login-container {
        background-color: rgb(255, 255, 255, 0.2);
        padding: 20px;
        border-radius: 10px;
        border: 0;
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        width: 500px;
        margin: 150px auto; /* 居中显示 */
        transition: transform 0.3s ease-in-out;
    }

    .login-container:hover {
        transform: scale(1.05);
    }

    .login-container h4 {
        text-align: center;
        margin-bottom: 20px;
        font-size: 25px;
    }
    .mylabel span{
        text-align: center;
        font-size: 20px;
    }
    .custom-input {
        margin: 10px;
        width: 240px;
    }
    .cus-button {
        margin: 20px 30px 20px 30px;
    }
    .link {
        text-decoration: none;
        color: #fff;
    }
</style>